package com.zefor.warns;

import com.grapecity.documents.excel.Q;
import com.zefor.utils.CacheUtil;
import kd.bos.cache.LocalMemoryCache;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.earlywarn.EarlyWarnContext;
import kd.bos.entity.earlywarn.warn.plugin.IEarlyWarnCustomReceiver;
import kd.bos.kdtx.common.exception.KdtxException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.drp.mdr.common.util.ObjectUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/*
 * 更新
 * */
public class EmployeeWarnReceiverPlugin implements IEarlyWarnCustomReceiver {
    // 获取缓存操作
    private final LocalMemoryCache localCache = CacheUtil.getCache();

    @Override
    public List<Long> getReceiverIds(EarlyWarnContext earlyWarnContext, DynamicObject[] dynamicObjects) {
        // 需要通知的人的id
        List<Long> receiverIds = new ArrayList<>();
        // 获取需要通知的内容
        DynamicObjectCollection warnDataList = earlyWarnContext.getWarnDataList();
        // 获取预警类型,查询预警标准
        String warnType = (String) localCache.get("WarnType");
        if (ObjectUtil.isEmpty(warnType)) {
            throw new KdtxException("未获取到预警类型");
        }
        // 查看用电量预警标准
        DynamicObject eleWarnStandard = BusinessDataServiceHelper.load("n716_warnstandard",
                "n716_mulilangtextfield,n716_decimalfield, n716_decimalfield1, n716_checkboxfield, n716_checkboxfield1,n716_combofield",
                new QFilter("n716_combofield", QCP.like, "%" + warnType + "%").toArray())[0];
        for (DynamicObject eleWarn : warnDataList) {
            // 获取勾选的负责人
            boolean flag1 = eleWarnStandard.getBoolean("n716_checkboxfield");
            boolean flag2 = eleWarnStandard.getBoolean("n716_checkboxfield1");
            // 获取栏舍信息
            DynamicObjectCollection corrals = eleWarn.getDynamicObjectCollection("n716_entryentity");
            // 查询到养殖厂信息
            DynamicObject farm = queryPicByCorralAndFormName("n716_farm",
                    (Long) eleWarn.getDynamicObject("n716_basedatafield").getPkValue());

            // 判断是否需要通知栏舍负责人
            if (flag1) {
                // 获取预警栏舍信息
                for (DynamicObject corral : corrals) {
                    // 获取负责人信息
                    DynamicObject pic = queryPicByCorralAndFormName("n716_corral",
                            (Long) corral.getDynamicObject("n716_basedatafield1").getPkValue());
                    // 把负责人id放入通知数组
                    receiverIds.add((Long) pic.getDynamicObject("n716_userfield").getPkValue());
                }
            }
            // 判断是否要通知养殖场负责人
            if (flag2) {
                // 查询到养殖厂信息
                receiverIds.add((Long) farm.getDynamicObject("n716_userfield").getPkValue());
            }
            // 如果触发了通知记录这个预警信息
            if (flag1 || flag2) {
                for (DynamicObject corral : corrals) {
                    // 获取栏舍信息
                    DynamicObject corralInfo = queryPicByCorralAndFormName("n716_corral",
                            (Long) corral.getDynamicObject("n716_basedatafield1").getPkValue());
                    // 保存信息
                    DynamicObject warnLog = BusinessDataServiceHelper.newDynamicObject("n716_warn_log");
                    // 因为这个方法会执行两次,当预警消息为空的时候停止记录
                    if (ObjectUtil.isEmpty(localCache.get(corral.getPkValue() + "warnMsg")))
                        break;
                    // 名称
                    warnLog.set("n716_textfield",
                            corralInfo.getString("name") + localCache.get(corral.getPkValue() + "warnMsg"));
                    localCache.remove(corral.getPkValue() + "warnMsg");
                    // 设置养殖场信息
                    warnLog.set("n716_basedatafield", farm);
                    // 设置栏舍
                    warnLog.set("n716_basedatafield1", corralInfo);
                    // 设置设备信息
                    DynamicObject[] equipment = BusinessDataServiceHelper
                            .load(
                                    "n716_dev_manager",
                                    "n716_basedatafield",
                                    new QFilter[] {
                                            new QFilter("n716_basedatafield1", QCP.equals, corralInfo.getPkValue())
                                    });
                    for (DynamicObject dynamicObject : equipment) {
                        // 电表
                        if (dynamicObject.getDynamicObject("n716_basedatafield").getString("name").contains("电")
                                && "用电".equals(warnType)) {
                            warnLog.set("n716_basedatafield2", dynamicObject.getDynamicObject("n716_basedatafield"));
                            break;
                        }
                        // 水表
                        if (dynamicObject.getDynamicObject("n716_basedatafield").getString("name").contains("水")
                                && "用水".equals(warnType)) {
                            warnLog.set("n716_basedatafield2", dynamicObject.getDynamicObject("n716_basedatafield"));
                            break;
                        }
                    }
                    // 设置单据状态
                    warnLog.set("billstatus", "A");
                    // 设置预警状态
                    warnLog.set("n716_combofield", "待解决");
                    // 设置预警类型
                    warnLog.set("n716_combofield1", warnType + "预警");
                    // 设置负责人
                    if (flag1 && flag2)
                        warnLog.set("n716_textfield1", corralInfo.getDynamicObject("n716_userfield").getString("name")
                                + "," + farm.getDynamicObject("n716_userfield").getString("name"));
                    else if (flag2)
                        warnLog.set("n716_textfield1", farm.getDynamicObject("n716_userfield").getString("name"));
                    else
                        warnLog.set("n716_textfield1", corralInfo.getDynamicObject("n716_userfield").getString("name"));
                    // 保存记录
                    SaveServiceHelper.saveOperate("n716_warn_log", new DynamicObject[] { warnLog },
                            OperateOption.create());
                }
            }
        }
        return receiverIds;
    }

    /*
     * 通过表单名称和id查询基础资料
     */
    private DynamicObject queryPicByCorralAndFormName(String formName, Long id) {
        DynamicObject[] load = BusinessDataServiceHelper.load(formName, "name,n716_userfield",
                new QFilter("id", QCP.equals, id).toArray());
        return load[0];
    }
}
